import React, { useState, useRef, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card } from '@/components/ui/card'
import { useToast } from '@/hooks/use-toast'

interface ImageSliceData {
  id: string
  x: number
  y: number
  width: number
  height: number
  name: string
}

interface ImageSlicerProps {
  imageUrl: string
  onSliceDataGenerated: (data: ImageSliceData[]) => void
}

export default function ImageSlicer({
  imageUrl,
  onSliceDataGenerated
}: ImageSlicerProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [imageLoaded, setImageLoaded] = useState(false)
  const [imageInfo, setImageInfo] = useState({ width: 0, height: 0 })
  const [gridConfig, setGridConfig] = useState({
    cols: 5,
    rows: 5,
    cellWidth: 28,
    cellHeight: 28,
    offsetX: 5,
    offsetY: 2,
    rowSpacing: 10,
    colSpacing: 10
  })
  const [previewImages, setPreviewImages] = useState<string[]>([])
  const [showGridOverlay, setShowGridOverlay] = useState(true)
  const { toast } = useToast()

  const loadImage = useCallback(async () => {
    const canvas = canvasRef.current
    if (!canvas) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    const img = new Image()
    img.crossOrigin = 'anonymous'

    img.onload = () => {
      setImageInfo({ width: img.width, height: img.height })
      canvas.width = img.width
      canvas.height = img.height
      ctx.drawImage(img, 0, 0)
      setImageLoaded(true)

      // 自动推测网格配置（如果当前是默认值28才进行推测）
      if (gridConfig.cellWidth === 28 && gridConfig.cellHeight === 28) {
        setGridConfig((prev) => ({
          ...prev,
          cellWidth: Math.max(gridConfig.cellWidth, 28), // 最小28px
          cellHeight: Math.max(gridConfig.cellHeight, 28) // 最小28px
        }))
      }
    }

    img.onerror = () => {
      toast({
        title: '图片加载失败',
        description: '请检查图片URL是否正确',
        variant: 'destructive'
      })
    }

    img.src = imageUrl
  }, [imageUrl, gridConfig.cellWidth, gridConfig.cellHeight, toast])

  const generatePreview = () => {
    const canvas = canvasRef.current
    if (!canvas || !imageLoaded) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    const {
      cols,
      rows,
      cellWidth,
      cellHeight,
      offsetX,
      offsetY,
      rowSpacing,
      colSpacing
    } = gridConfig
    const previews: string[] = []

    // 创建临时 canvas 用于切图
    const tempCanvas = document.createElement('canvas')
    const tempCtx = tempCanvas.getContext('2d')
    if (!tempCtx) return

    tempCanvas.width = cellWidth
    tempCanvas.height = cellHeight

    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const x = offsetX + col * (cellWidth + colSpacing)
        const y = offsetY + row * (cellHeight + rowSpacing)

        // 检查是否超出图片边界
        if (
          x + cellWidth > imageInfo.width ||
          y + cellHeight > imageInfo.height
        ) {
          break
        }

        // 清空临时 canvas
        tempCtx.clearRect(0, 0, cellWidth, cellHeight)

        // 切出小图
        tempCtx.drawImage(
          canvas,
          x,
          y,
          cellWidth,
          cellHeight,
          0,
          0,
          cellWidth,
          cellHeight
        )

        previews.push(tempCanvas.toDataURL('image/png'))
      }
    }

    setPreviewImages(previews)
  }

  const generateSliceData = () => {
    const {
      cols,
      rows,
      cellWidth,
      cellHeight,
      offsetX,
      offsetY,
      rowSpacing,
      colSpacing
    } = gridConfig
    const sliceData: ImageSliceData[] = []

    let id = 1
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const x = offsetX + col * (cellWidth + colSpacing)
        const y = offsetY + row * (cellHeight + rowSpacing)

        // 检查是否超出图片边界
        if (
          x + cellWidth > imageInfo.width ||
          y + cellHeight > imageInfo.height
        ) {
          break
        }

        sliceData.push({
          id: id.toString(),
          x,
          y,
          width: cellWidth,
          height: cellHeight,
          name: `slice_${id}`
        })
        id++
      }
    }

    onSliceDataGenerated(sliceData)

    // 复制到剪贴板
    navigator.clipboard.writeText(JSON.stringify(sliceData, null, 2))
    toast({
      title: '配置已生成',
      description: '切图数据已复制到剪贴板'
    })
  }

  // 绘制网格覆盖层
  const drawGridOverlay = useCallback(() => {
    const canvas = canvasRef.current
    if (!canvas || !imageLoaded) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    // 重新绘制原图
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.onload = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(img, 0, 0)

      if (showGridOverlay) {
        const {
          cols,
          rows,
          cellWidth,
          cellHeight,
          offsetX,
          offsetY,
          rowSpacing,
          colSpacing
        } = gridConfig

        // 绘制网格
        ctx.strokeStyle = '#ff0000'
        ctx.lineWidth = 1

        for (let row = 0; row < rows; row++) {
          for (let col = 0; col < cols; col++) {
            const x = offsetX + col * (cellWidth + colSpacing)
            const y = offsetY + row * (cellHeight + rowSpacing)

            // 检查是否超出图片边界
            if (
              x + cellWidth > imageInfo.width ||
              y + cellHeight > imageInfo.height
            ) {
              break
            }

            ctx.strokeRect(x, y, cellWidth, cellHeight)
          }
        }
      }
    }
    img.src = imageUrl
  }, [imageLoaded, showGridOverlay, gridConfig, imageInfo, imageUrl])

  useEffect(() => {
    loadImage()
  }, [loadImage])

  useEffect(() => {
    drawGridOverlay()
  }, [drawGridOverlay])

  return (
    <Card className="p-6">
      <h2 className="mb-4 text-xl font-semibold">图片切割工具</h2>

      <div className="space-y-6">
        {/* 图片信息 */}
        {imageLoaded && (
          <div className="text-sm text-gray-600">
            图片尺寸: {imageInfo.width} × {imageInfo.height} 像素
          </div>
        )}

        {/* 网格配置 */}
        <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
          <div>
            <label className="mb-1 block text-sm font-medium">列数</label>
            <Input
              type="number"
              value={gridConfig.cols}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  cols: parseInt(e.target.value) || 1
                }))
              }
              min="1"
              max="20"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">行数</label>
            <Input
              type="number"
              value={gridConfig.rows}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  rows: parseInt(e.target.value) || 1
                }))
              }
              min="1"
              max="20"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">切片宽度</label>
            <Input
              type="number"
              value={gridConfig.cellWidth}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  cellWidth: parseInt(e.target.value) || 1
                }))
              }
              min="1"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">切片高度</label>
            <Input
              type="number"
              value={gridConfig.cellHeight}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  cellHeight: parseInt(e.target.value) || 1
                }))
              }
              min="1"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">X偏移</label>
            <Input
              type="number"
              value={gridConfig.offsetX}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  offsetX: parseInt(e.target.value) || 0
                }))
              }
              min="0"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">Y偏移</label>
            <Input
              type="number"
              value={gridConfig.offsetY}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  offsetY: parseInt(e.target.value) || 0
                }))
              }
              min="0"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">行间距</label>
            <Input
              type="number"
              value={gridConfig.rowSpacing}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  rowSpacing: parseInt(e.target.value) || 0
                }))
              }
              min="0"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium">列间距</label>
            <Input
              type="number"
              value={gridConfig.colSpacing}
              onChange={(e) =>
                setGridConfig((prev) => ({
                  ...prev,
                  colSpacing: parseInt(e.target.value) || 0
                }))
              }
              min="0"
            />
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="flex gap-2">
          <Button onClick={generatePreview} variant="outline">
            生成预览
          </Button>
          <Button onClick={generateSliceData}>生成配置</Button>
          <Button
            onClick={() => setShowGridOverlay(!showGridOverlay)}
            variant="outline"
          >
            {showGridOverlay ? '隐藏' : '显示'}网格
          </Button>
        </div>

        {/* 原图预览 */}
        <div>
          <h3 className="mb-2 text-sm font-medium">原图预览</h3>
          <div className="max-h-96 overflow-auto rounded border bg-gray-50 p-2">
            <canvas
              ref={canvasRef}
              className="h-auto max-w-full border"
              style={{ imageRendering: 'pixelated' }}
            />
          </div>
        </div>

        {/* 切片预览 */}
        {previewImages.length > 0 && (
          <div>
            <h3 className="mb-2 text-sm font-medium">
              切片预览 ({previewImages.length} 个切片)
            </h3>
            <div className="grid max-h-64 grid-cols-8 gap-2 overflow-auto rounded border bg-gray-50 p-4">
              {previewImages.map((preview, index) => (
                <div
                  key={index}
                  className="flex size-12 items-center justify-center rounded border bg-white"
                  title={`切片 ${index + 1}`}
                >
                  <img
                    src={preview}
                    alt={`切片 ${index + 1}`}
                    className="max-h-full max-w-full object-contain"
                    style={{ imageRendering: 'pixelated' }}
                  />
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </Card>
  )
}
